package com.iwhalecloud.bss.kite.cucc.service.batch.task;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.executor.enums.ExecutorTypeEmun;
import com.iwhalecloud.bss.kite.common.executor.task.ExecuteTask;
import com.iwhalecloud.bss.kite.common.executor.vo.ExecuteResult;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.zsmart.core.exception.ExceptionUtil;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/6/4
 * @Package com.iwhalecloud.bss.kite.cucc.service.batch.executor.task
 */
public class InputCheckDataTask extends ExecuteTask {
    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(InputCheckDataTask.class);
    private List<String> data;
    private KiteBatchAcceptDetail detail;
    private Map<String, KiteAttr> kiteAttrMap;
    private List<String> titleList;
    private KiteProdInst prodInst;
    private List<KiteAttrDTO> keyAttrs;
    private String provinceName;

    public InputCheckDataTask(ExecutorTypeEmun typeEmun, String taskId, List<String> data, KiteBatchAcceptDetail detail,
                              Map<String, KiteAttr> kiteAttrMap, List<String> titleList, KiteProdInst prodInst, List<KiteAttrDTO> keyAttrs,
                              String provinceName) {
        super.setTypeEmun(typeEmun);
        super.setTaskId(taskId);
        this.data = data;
        this.detail = detail;
        this.kiteAttrMap = kiteAttrMap;
        this.titleList = titleList;
        this.prodInst = prodInst;
        this.keyAttrs = keyAttrs;
        this.provinceName = provinceName;
    }

    @Override
    public ExecuteResult<String> call() {
        long start = System.currentTimeMillis();
        ExecuteResult<String> result = new ExecuteResult<>();
        try {
            KiteProdInst temporaryInst = KiteObjectUtils.clone(prodInst);
            StringBuffer resultBuffer = new StringBuffer();
            for (int j = 0; j < data.size(); j++) {
                String value = data.get(j);
                if (titleList.size() < j) {
                    break;
                }
                String title = titleList.get(j);
                // 如果是省市区截取第一段省，校验是否跨域
                if (KiteStringUtils.contains(title, "省市区")) {
                    if (!KiteStringUtils.equals(provinceName, KiteStringUtils.substringBefore(value, Symbols.SLASH))) {
                        resultBuffer.append("批量业务不允许受理跨域业务，请重新录入省市区信息！");
                    }
                    continue;
                }
                if (KiteStringUtils.contains(title, "装机地址") && KiteStringUtils.isBlank(value)) {
                    resultBuffer.append("装机地址不能为空");
                }
                // 校验模版必填属性值是否为空
                if (title.contains(Symbols.STAR) && KiteStringUtils.isBlank(value)) {
                    resultBuffer.append("\"").append(title).append("\"").append("不能为空;");
                }
                title = title.trim().replace("*", "");
                title = title.trim().replace("\n", "");
                // 校验属性是否存在
                KiteAttr kiteAttr = kiteAttrMap.get(title);
                if (Objects.isNull(kiteAttr)) {
                    resultBuffer.append("属性").append("\"").append(title).append("\"").append("不存在;");
                    continue;
                }
                // 校验导入的关键属性是否与商品选择时一致
                KiteAttrDTO keyAttr = keyAttrs.stream()
                    .filter(attr -> KiteStringUtils.equals(attr.getFieldName(), kiteAttr.getFieldName())).findFirst()
                    .orElse(null);
                if (Objects.nonNull(keyAttr) && !KiteStringUtils.equals(value, keyAttr.getValueDesc())) {
                    resultBuffer.append("导入的关键属性\"").append(title).append("\"").append("与选商品时的关键属性不一致");
                }
                // 校验是否符合正则表达式
                String format = kiteAttr.getAttrFormat();
                if (KiteStringUtils.isNotBlank(format) && !isFilter(kiteAttr.getFieldName())
                    && KiteStringUtils.isNotEmpty(value)) {
                    Pattern pattern = Pattern.compile(format);
                    Matcher matcher = pattern.matcher(value);
                    if (!matcher.matches()) {
                        resultBuffer.append("\"").append(title).append("\"").append(kiteAttr.getCheckMessage())
                            .append(";");
                    }
                }
                // 回填属性到实例中
                KiteAttr temporaryAttr = KiteObjectUtils.clone(kiteAttr);
                temporaryAttr.setValue(value);
                temporaryInst.setAttr(temporaryAttr);
            }

            List<KiteAttr> tempAttrList = temporaryInst.listAttrs();
            for (KiteAttr attr : tempAttrList) {
                if (isFilter(attr.getFieldName())) {
                    continue;
                }
                // 校验规格必填属性值是否为空
                if (KiteStringUtils.isBlank(attr.getValue())
                    && !KiteStringUtils.equalsAny(attr.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_E,
                    KeyConsts.PROD_ATTR_SHOW_TYPE_H)
                    && KiteStringUtils.equals(attr.getIsNull(), KeyConsts.IFTRUE_F)) {
                    resultBuffer.append("必填属性\"").append(attr.getCname()).append("\",").append("编码:")
                        .append(attr.getFieldName()).append(",不能为空;");
                }
                // 校验导入属性是否是枚举值
                if (KiteStringUtils.isNotBlank(attr.getValue()) && KiteListUtils.isNotEmpty(attr.getAttrValues())
                    && KiteStringUtils.equals(attr.getAttrValueTypeId(), "98A")) {
                    if (attr.getAttrValues().stream().noneMatch(attrValue -> KiteStringUtils.equalsAny(attr.getValue(),
                        attrValue.getAttrValue(), attrValue.getAttrValueName()))) {
                        resultBuffer.append("属性\"").append(attr.getCname()).append("\",").append("编码:")
                            .append(attr.getFieldName()).append(",导入的值").append(attr.getValue()).append("不是此属性的枚举值;");
                    }
                }
            }
            if (KiteStringUtils.isEmpty(resultBuffer.toString())) {
                BatchAcceptUtil.delDetailResult(detail, "校验成功", LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1200);
            }
            else {
                BatchAcceptUtil.delDetailResult(detail, resultBuffer.toString(), LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1100);
            }
        }
        catch (Exception e) {
            LOGGER.error("ExecuteResult-->", e, e.getMessage());
            BatchAcceptUtil
                .delDetailResult(detail, ExceptionUtil.exToString(e), LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1100);
        }

        long end = System.currentTimeMillis();
        long times = end - start;
        System.out.println(taskId + "耗时："+ times);
        return result;

    }

    private boolean isFilter(String fieldName) {
        return KiteStringUtils.equalsAny(fieldName, "2_0000211", "2_0000117", "2_0000111", "2_0000109", "2_0000222",
            "2_0000209", "2_0000105");
    }
}
